<?php

namespace app\admin\model;

use think\Model;
use think\facade\Request;
use think\facade\Config;

/**
 * 错误次数模型
 */
class Error extends Model
{
    /**
     * 数据表名称
     * @var string
     */
    protected $name = 'admin_error';

    /**
     * 检测错误次数
     * @param  string $command 命令
     * @param  integer $errors 错误次数
     * @return boolean
     */
    public static function check($command, $errors = 0)
    {
        if ($errors == 0){
            $errors = Config::get('xp.errors');
        }
        $today = (int)date('Ymd');
        $db = self::where('ip', '=', Request::ip())->where('command', '=', $command)->where('dateline', '=', $today)->find();
        if ($db && $db['errors'] >= $errors) {
            return true;
        }
        return false;
    }

    /**
     * 清除错误次数
     * @param  string $command 命令
     * @return void
     */
    public static function clear($command)
    {
        $today = (int)date('Ymd');
        $db = self::where('ip', '=', Request::ip())->where('command', '=', $command)->where('dateline', '=', $today)->find();
        if ($db) {
            $db->delete();
        }
    }

    /**
     * 添加错误次数
     * @param  string $command 命令
     * @return void
     */
    public static function add($command)
    {
        $today = (int)date('Ymd');
        $ip = Request::ip();
        $db = self::where('ip', '=', $ip)->where('command', '=', $command)->where('dateline', '=', $today)->find();
        if ($db) {
            $db->errors += 1;
            $db->save();
        } else {
            $obj = new self;
            $obj->save([
                'ip' => $ip,
                'command' => $command,
                'errors' => 1,
                'dateline' => $today,
            ]);
        }
    }
}
